package problems

import (
	"fmt"
	"html/template"
	"myOJ/coderun"
	"myOJ/datastructure"
	"myOJ/db"
	"myOJ/db/getproblem"
	"myOJ/makehintcode"
	"net/http"
	"strings"
)

func ProblemsPage(w http.ResponseWriter, r *http.Request) {

	plombleTitle := r.FormValue("problem")

	pd, err := getproblem.GetProblem(plombleTitle)
	if err != nil {
		fmt.Println(err)
		return
	}
	pageContent := datastructure.ProblemPage{pd, makehintcode.MakePYHint(plombleTitle)}

	t := template.Must(template.ParseFiles("view/problempage/problempage.html"))
	t.Execute(w, &pageContent)
}

type CodeResult struct {
	Result string
}

func CodePost(w http.ResponseWriter, r *http.Request) {

	cook := r.Header.Get("Cookie")

	if strings.Compare(strings.TrimSpace(cook), "") != 0 {
		t := template.Must(template.ParseFiles("view/problempage/codepost.html"))

		accountName := strings.Split(cook, "=")[0]
		postCode := r.FormValue("code")
		ptitle := r.FormValue("problem")
		res := coderun.RunCode(postCode, ptitle)

		db.PushCode(accountName, ptitle, postCode, "python", res)
		cr := CodeResult{fmt.Sprintf("%.2f", res) + "%通过"}
		t.Execute(w, &cr)

	} else {
		t := template.Must(template.ParseFiles("view/loginpage/loginPlease.html"))
		t.Execute(w, nil)
	}
}
